using System;
using System.Collections.Generic;
using System.Text;

using Csla;
using Csla.Data;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;

namespace buildingLib.human
{
    [Serializable()]
    public class DepartEmployees : NameValueListBase<Guid, string>
    {
        #region Factory Methods

        private static DepartEmployees _list = null;
        private static DepartEmployees _readyList=null;

        public static DepartEmployees GetEmployees(string depart)
        {
            if (_list == null)
                _list = DataPortal.Fetch<DepartEmployees>(
                  new ReadyCriteria(depart, false));
            return _list;
        }

        public static DepartEmployees GetReadyEmployees(string depart)
        {
            if (_readyList == null)
                _readyList = DataPortal.Fetch<DepartEmployees>(
                  new ReadyCriteria(depart, true));
            return _readyList;
        }

        public static void InvalidateCache()
        {
            _list = null;
            _readyList = null;
        }

        

        private DepartEmployees()
        { /* require use of factory methods */ }

        #endregion

        #region Data Access
        [Serializable()]
        private  class ReadyCriteria
        {
            private string _depart;
            public string Depart
            {
                get { return _depart; }
            }

            private bool _isReady;

            public bool IsReady
            {
                get { return _isReady; }
            }

            public ReadyCriteria(string depart, bool isReady)
            {
                _depart = depart;
                _isReady = isReady;
            }
        }



        private void DataPortal_Fetch(ReadyCriteria criteria)
        {
            RaiseListChangedEvents = false;
            IsReadOnly = false;
            // TODO: load values
            Database db = SQLDatabase.GetDatabase();
            DbCommand dbcom = criteria.IsReady ?
                db.GetStoredProcCommand("usp_GGetReadyEmployeesByDepart") : 
                db.GetStoredProcCommand("usp_GGetEmployeesByDepart");
            db.AddInParameter(dbcom, "depart", DbType.String, criteria.Depart);
            using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(dbcom)))
            {
                while (dr.Read())
                {
                    Add(new NameValueListBase<Guid, string>.
                      NameValuePair(dr.GetGuid("id"),dr.GetString("name")));
                }
            }
            IsReadOnly = true;
            RaiseListChangedEvents = true;
        }
        #endregion
    }
}
